import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";

export class HarmonyPilotProvider implements vscode.WebviewViewProvider {
  _view?: vscode.WebviewView;
  _doc?: vscode.TextDocument;
  context: vscode.ExtensionContext;

  constructor(
    private readonly _extensionUri: vscode.Uri,
    context: vscode.ExtensionContext
  ) {
    this.context = context;
  }

  public resolveWebviewView(webviewView: vscode.WebviewView) {
    this._view = webviewView;

    webviewView.webview.options = {
      // 在 webview 允许脚本
      enableScripts: true,
      localResourceRoots: [this._extensionUri],
    };

    const html = this.getHtmlForWebview(webviewView.webview);
    webviewView.webview.html = html;
    webviewView.webview.onDidReceiveMessage(
      (message) => {
        console.log(message)
      },
      undefined,
      this.context.subscriptions
    );

  }

  private getHtmlForWebview(webview: vscode.Webview) {
    const code = fs.readFileSync(
      path.resolve(__dirname, "index.html"),
      "utf-8"
    );
    const files = fs.readdirSync(path.resolve(__dirname, "assets"));
    let jsFile = "";
    let cssFile = "";
    for (const file of files) {
      if (file.endsWith("js")) {
        jsFile = file;
      } else if (file.endsWith("css")) {
        cssFile = file;
      } else {
      }
    }
    const curPath = vscode.Uri.joinPath(
      this._extensionUri,
      "dist/assets",
      jsFile
    );
    const curCssPath = vscode.Uri.joinPath(
      this._extensionUri,
      "dist/assets",
      cssFile
    );
    const jsSrc = this._view?.webview.asWebviewUri(curPath);
    const cssSrc = this._view?.webview.asWebviewUri(curCssPath);
    let result = code.replace(/<script.*?src="(.*?)">/g, (curStr: string) => {
      return curStr.replace(/src="(.+?)"/, (src: string) => {
        return `src="${jsSrc}"`;
      });
    });
    result = result.replace(/<link.*?href="(.*?)">/g, (curStr: string) => {
      return curStr.replace(/href="(.+?)"/, (src: string) => {
        return `href="${cssSrc}"`;
      });
    });
    return result;
  }
}
